package com.ruslan.magaz.web;


import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.ruslan.magaz.domain.Cart;
import com.ruslan.magaz.domain.Category;
import com.ruslan.magaz.domain.Customer;
import com.ruslan.magaz.domain.Product;
import com.ruslan.magaz.domain.Rating;
import com.ruslan.magaz.domain.User;
import com.ruslan.magaz.service.ItemService;
import com.ruslan.magaz.service.OrderService;
import com.ruslan.magaz.service.UserService;

@Controller
@RequestMapping("/products")
public class ProductsController {
	public static int PRODUCTS_PAGE_SIZE = 20;
	public static int REVIEWS_PAGE_SIZE = 4;

	@Autowired
	private UserService userService;
	
	@Autowired
	private ItemService itemService;
	
	@Autowired
	private OrderService orderService;
	
	
	@ModelAttribute("categories")
	 public List<Category> getAllCategories() {
	  return itemService.getAllCategories();
	}
	
	
	@ModelAttribute("user")
	 public User getUser(HttpServletRequest req) throws Exception {
		HttpSession session = req.getSession(false);
		if (session == null){
			return new User();
		}
		Object currentUserId = session.getAttribute("userId");
		if (currentUserId == null){
			return new User();
		}
		return userService.getUserById((Integer) currentUserId);
	}
		
	
	@RequestMapping(value="")
    public String showProducts(HttpServletRequest req, HttpServletResponse res, @RequestParam int categoryId, @RequestParam(required = false) Integer pageNum, Model model) throws ServletException, IOException{
			if (pageNum == null){
				pageNum=1;
			}
			int lastPageNum = itemService.productsForCategoryPageCount(categoryId, PRODUCTS_PAGE_SIZE);
	 		List<Product> products = itemService.getAllProductsForCategory(categoryId, pageNum, PRODUCTS_PAGE_SIZE);
	 		model.addAttribute("products", products);
	 		model.addAttribute("lastPageNum", lastPageNum);
	 		model.addAttribute("categoryId", categoryId);
	        return "tiles/products";
	 }
	
	@RequestMapping(value="view", method = RequestMethod.GET)
    public String viewItem(HttpServletRequest req, HttpServletResponse res, @RequestParam Integer itemId,  @RequestParam(required = false) Integer pageNum, Model model) throws ServletException, IOException{
		if (pageNum == null){
			pageNum=1;
		}
		HttpSession session = req.getSession(true);
		Cart cart = (Cart) session.getAttribute("cart");
		if (cart == null){
			cart = new Cart();
			session.setAttribute("cart", cart);
		}
		if (session.getAttribute("userId") == null){
			model.addAttribute("hideRate", true);
		}
		Product product = itemService.getProductById(itemId);
		if (product == null){
			return "redirect:/home";
		}
		int lastPageNum = itemService.reviewsForProductPageCount(itemId, REVIEWS_PAGE_SIZE);
		Count count = new Count();
		count.setCount(cart.getProductCount(itemId));
		count.setProductId(itemId);
 		List<Rating> ratings = itemService.getAllReviewsForProduct(itemId, pageNum, REVIEWS_PAGE_SIZE);
 		product.setRatings(itemService.sortRatings(ratings));
 		int mark = (int) Math.round(itemService.getAvgRating(itemId));
 		int voters = itemService.countRaters(itemId);
 		model.addAttribute("product", product);
 		model.addAttribute("mark",mark);
 		model.addAttribute("voters",voters);
 		model.addAttribute("count",count);
 		model.addAttribute("lastPageNum", lastPageNum);
 		return "tiles/item";
	 }
	
	@RequestMapping(value="view", method = RequestMethod.POST)
    public String addItemToCart(HttpServletRequest req, HttpServletResponse res, Model model, @RequestParam Integer itemId,  @RequestParam(required = false) Integer pageNum, @Valid @ModelAttribute Count count, BindingResult bindingResult) throws ServletException, IOException{
			if (pageNum == null){
				pageNum=1;
			}
			HttpSession session = req.getSession(false);
			Cart cart = (Cart) session.getAttribute("cart");
			if (session.getAttribute("userId") == null){
				model.addAttribute("hideRate", true);
			}
	 		Product product = itemService.getProductById(itemId);
	 		int mark = (int) Math.round(itemService.getAvgRating(itemId));
	 		int voters = itemService.countRaters(itemId);
	 		List<Rating> ratings = itemService.getAllReviewsForProduct(itemId, pageNum, REVIEWS_PAGE_SIZE);
	 		product.setRatings(itemService.sortRatings(ratings));
	 		model.addAttribute("product", product);
	 		model.addAttribute("mark",mark);
	 		model.addAttribute("voters",voters);
	 		model.addAttribute("count",count);
	 		if(bindingResult.hasErrors()){
	 			return"tiles/item";
	 		}
	 		cart.setProductCount(itemId, count.getCount());
	 		return "tiles/item";
	 }
	
	@RequestMapping(value="/rate", method = RequestMethod.GET)
    public String rateItem(HttpServletRequest req, HttpServletResponse res, @RequestParam Integer itemId, Model model) throws ServletException, IOException{
			HttpSession session = req.getSession(false);
			if (!UserController.isLoggedIn(req)){
				String referer = req.getHeader("Referer");
				return "redirect:"+ referer;
			}
			int currentUserId = (Integer) session.getAttribute("userId");
			Rating rating = itemService.getRatingForUserNItem(currentUserId, itemId);
			if (itemService.getProductById(itemId) == null){
				return "redirect:/home";
			}
			if (rating == null){
				rating = new Rating(0);
			}
			model.addAttribute("itemId", itemId);
			model.addAttribute("rating", rating);
//			model.addAttribute("review", review);
	 		return "tiles/reviewForm";
	}
	@RequestMapping(value="/rate", method = RequestMethod.POST)
    public String rateItemPost(HttpServletRequest req, HttpServletResponse res, Model model, @RequestParam Integer itemId, @Valid @ModelAttribute Rating rating, BindingResult bindingResult) throws ServletException, IOException{
		if(bindingResult.hasErrors()){
			 return"tiles/reviewForm";
		 }
			HttpSession session = req.getSession(false);
			int currentUserId = (Integer) session.getAttribute("userId");
//			User user = userService.getUserById(userId);
//			Product product = itemService.getProductById(itemId);
			rating.setUser(new User(currentUserId));
			rating.setProduct(new Product(itemId));
			rating.setReviewDate(new Date());
			if (rating.getRatingId()!=0){
				itemService.editRating(rating);
			}else{
				itemService.addRating(rating);
			}
//			String referer = req.getHeader("Referer");
			return "redirect:/products/view?itemId="+itemId;
	 }
//	@RequestMapping(value="view", method = RequestMethod.POST)
//    public String addToCart(HttpServletRequest req, HttpServletResponse res, @ModelAttribute("count") int count, Model model) throws ServletException, IOException{
//			
//	 		if (LoginController.isLogedIn(req)){
//	        	return "logedIn/item";
//	        }else{
//	        	return "anonymous/item";
//	        }
//	 }
	
	
}
